package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private SeckillVoucherServiceImpl seckillVoucherServiceImpl;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private  VoucherOrderServiceImpl voucherOrderServiceImpl;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;


    //加载lua脚本
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //阻塞队列
    private BlockingQueue<VoucherOrder> orderTasks =new ArrayBlockingQueue<>(1024 * 1024);
    //异步处理线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void init(){
        //线程池去提交任务↓↓↓
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }
    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true) {
                log.info("开启异步线程处理订单到数据库。。。。。。。。");

                try {
                    //获取阻塞队列中的信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    // 2.创建订单
                    handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                }
            }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        //创建分布式锁对象
        //  SimpleRedisLock simpleRedisLock=new SimpleRedisLock("order"+UserHolder.getUser().getId(),stringRedisTemplate);
        //创建分布式锁对象redission
        RLock lock = redissonClient.getLock("order" + voucherOrder.getUserId());

        //通过分布式锁对象获取锁
        boolean isLock = lock.tryLock();
        if (!isLock){
            log.error("不允许重复下单！");
            return;
        }
      //  synchronized (UserHolder.getUser().getId().toString().intern()) { //(悲观锁针对个人用户的并发)   intern确保是锁这个值(id)而不是对象
            //只有spring容器中的bean对象调用方法才能实现Transactional事务功能，直接调用是目标对象调用方法不会实现Transactional事务功能，
            // 所以这里我用的是依赖注入自身impl对象进行方法调用，和官方不同。
            try {
                 voucherOrderServiceImpl.createVoucherOrder(voucherOrder);
            } finally {
                //手动释放分布式锁
                lock.unlock();
            }
    //    }
    }

    /**
     * 异步秒杀优惠券 ---优化
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {

        //1.执行lua脚本   (redis里的操作)
        Long LuaResult = stringRedisTemplate.execute(
                SECKILL_SCRIPT, Collections.EMPTY_LIST,
                voucherId.toString(),
                UserHolder.getUser().getId().toString());
        if (LuaResult.intValue()!=0){//Lua脚本执行 若不为0 那么代表不能下单 库存不足or不能重复下单
            return Result.fail(LuaResult.intValue()==1 ? "优惠券已售空~":"一个用户只能买一张！！！！");
        }

        long OrderId = redisIdWorker.nextId("order");

        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setCreateTime(LocalDateTime.now());
        voucherOrder.setId(OrderId);
        voucherOrder.setUserId(UserHolder.getUser().getId());

        //添加voucherOrder 即放入阻塞队列
        orderTasks.add(voucherOrder);

        return Result.ok(OrderId);

    }

    /**
     * 优惠券秒杀
     * @param voucherId
     * @return
    @Override
    public Result seckillVoucher(Long voucherId) {
        //1.查询优惠券
        SeckillVoucher seckillVoucher = seckillVoucherServiceImpl.getById(voucherId);
        //判读该优惠券的库存、时间是否满足
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())){
            return Result.fail("秒杀尚未开始！");
        }
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("秒杀已经结束！");
        }
        if (seckillVoucher.getStock()<1){
            return Result.fail("优惠券已售空~");
        }

        //创建分布式锁对象
      //  SimpleRedisLock simpleRedisLock=new SimpleRedisLock("order"+UserHolder.getUser().getId(),stringRedisTemplate);

        //创建分布式锁对象redission
        RLock lock = redissonClient.getLock("order" + UserHolder.getUser().getId());

        //通过分布式锁对象获取锁
        boolean isLock = lock.tryLock();
        if (!isLock){
            return Result.fail("一个用户只能买一张！！！！");
        }
        synchronized (UserHolder.getUser().getId().toString().intern()) { //(悲观锁针对个人用户的并发)   intern确保是锁这个值(id)而不是对象
            //只有spring容器中的bean对象调用方法才能实现Transactional事务功能，直接调用是目标对象调用方法不会实现Transactional事务功能，
            // 所以这里我用的是依赖注入自身impl对象进行方法调用，和官方不同。
            try {
                return voucherOrderServiceImpl.createVoucherOrder(voucherId);
            } finally {
                //手动释放分布式锁
                lock.unlock();
            }
        }
    }*/



    /**
     * 创建优惠券订单，即实现售卖优惠券
     * @param voucherOrder
     * @return
     */
    @Transactional
    public Result createVoucherOrder(VoucherOrder voucherOrder) {

            //判断一人一单  即根据uerID和orderID去查优惠券的order表
            VoucherOrder voucherOrder1 = this.query().eq("voucher_id", voucherOrder.getVoucherId()).eq("user_id", voucherOrder.getUserId()).one();
            if (voucherOrder1 != null) {
                return Result.fail("一个用户只能买一张！！！！");
            }

            //用mybatis-plus更新数据库 把优惠券的数量减一
            boolean success = seckillVoucherServiceImpl.update()
                    .setSql("stock=stock-1")
                    .eq("voucher_id",  voucherOrder.getVoucherId())
                    // .eq("stock",seckillVoucher.getStock())  //CAS(查看当前的stock是否和刚开始查询到的stock一致-----不太好  会导致经常买不到券)
                    .gt("stock", 0)                //CAS改进(只需要判断此时表中的stock的券是否大大于0即可-----解决上述的问题)
                    .update();
            if (!success) {
                return Result.fail("优惠券已售空");
            }
            //将数据保存到订单表
            this.save(voucherOrder);
            return Result.ok(voucherOrder.getId());

    }
}
